<template>
  <div class="select-tree-component">
    <FormItemView v-bind="$attrs" :selecting="selecting" :value="valueText" @click="handleOpen" />

    <staff-template-input ref="StaffTemplateInputRef" :type="type" :title="title" @close="selecting = false" @groupAdd="handleGroupAdd" />
    <create-group ref="CreateGroupRef" />
  </div>
</template>

<script>
import StaffTemplateInput from './template'
import FormItemView from '@/components/FormItemView'
import CreateGroup from '@/containers/Group/create'
export default {
  name: 'StaffTemplateView',
  components: { StaffTemplateInput, FormItemView, CreateGroup },
  props: {
    value: {
      type: Array,
      default: () => []
    },
    optionList: {
      type: Array,
      default: () => []
    },
    placeholder: {
      type: String,
      default: () => '请选择'
    },
    title: {
      type: String,
      default: '请选择'
    },
    type: {
      type: Array,
      default: () => [1, 3] // 1. 组织架构 2. 职务 3.群组
    }

  },
  data() {
    return {
      selecting: false
    }
  },
  computed: {
    valueText: function() {
      const { value } = this.$props
      if (value.length === 0) {
        return ''
      }
      // ####mark 此处的显示人数 不太准确 , 有可能会选择 群组
      return '已选' + value.length + '人'
    }
  },
  methods: {
    handleOpen() {
      this.$data.selecting = true
      const _value = this.formatBefore(this.$props.value)
      this.$refs.StaffTemplateInputRef.open(_value).then(res => {
        const data = this.formatAfter(res)
        this.$emit('input', data, res)
        this.$emit('change', data, res)

        this.$data.selecting = false
      })
    },
    formatBefore(data) {
      const orgList = data.filter(e => e.notifyTargetType === 1).map(e => e.notifyTargetId)
      const groupList = data.filter(e => e.notifyTargetType === 3).map(e => e.notifyTargetId)
      return { orgList, groupList }
    },
    formatAfter(data) {
      const orgList = data.orgList.map(e => {
        return {
          notifyTargetType: 1,
          notifyTargetDeptId: e.parentDeptId,
          notifyTargetId: e.id
        }
      })
      const groupList = data.groupList.map(e => {
        return { notifyTargetType: 3, notifyTargetId: e }
      })

      return [...orgList, ...groupList]
    },
    handleGroupAdd() {
      this.$refs.CreateGroupRef.open().then(() => {
        this.$refs.StaffTemplateInputRef.postGroupList()
      })
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
